package com.moleq.mgpos.activities;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.adapter.SelectionAdapter;
import com.moleq.adapter.StateListAdapter;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.models.AdapterDataSourceBuilder;
import com.moleq.models.CustomerSetting;
import com.moleq.models.GlobalInfo;
import com.moleq.models.States;
import com.moleq.service.CustomerSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.service.StatesService;
import com.moleq.util.MoleQUtil;

public class CustomerSettingActivity extends Activity {

	public static final int CustomerID = 0;
	public static final int FirstName = 1;
	public static final int LastName = 2;
	private List<States> listStates = null;
	private StatesService statesService = null;
	private StateListAdapter stateAdapter = null;
	private Spinner sp_condition;
	private String[] sp_items;
	private Button btn_search, btn_state, btn_undo, btn_save, btn_exit,
			btn_states_dialog_ok, btn_states_dialog_cancel,
			btn_states_dialog_search;
	private ListView lv_customer_list, lv_states_dialog_list;
	private BeepImageButton iv_add;
	private TextView tv_page;
	private ImageButton ibtn_backpage, ibtn_nextpage;
	private EditText et_search, et_first_name, et_last_name, et_address_1,
			et_address_2, et_city, et_zip, et_telephone, et_email,
			et_states_dialog_search, et_customer_no;
	private LinearLayout ll_main;
	private MessageDialog mMessageDialog;
	private CustomerSettingService customerSettingService = null;
	private List<CustomerSetting> customerList = null;
	private SelectionAdapter customerListAdapter = null;
	public boolean isExit = false, is_Insert = false;
	public int PageCountSize = 0;
	public String pageString, SearchText;
	public int SearchType;
	private static final int PageSize = 25;
	public static boolean CustomerMode = false;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customer_setting);

		customerSettingService = ServiceManager.getInstance().mCustomerSettingService;
		statesService = ServiceManager.getInstance().mStatesService;

		BindControls();
		sp_items = getResources().getStringArray(R.array.sp_customer_type);
		ArrayAdapter<String> SpAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sp_items);
		SpAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_condition.setAdapter(SpAdapter);
		InitializationFalse();
	}

	public void BindControls() {
		ll_main = (LinearLayout) this.findViewById(R.id.ll_main);
		sp_condition = (Spinner) this.findViewById(R.id.sp_condition);
		tv_page = (TextView) this.findViewById(R.id.tv_page);
		lv_customer_list = (ListView) this.findViewById(R.id.lv_customer_list);
		btn_search = (Button) this.findViewById(R.id.btn_search);
		btn_state = (Button) this.findViewById(R.id.btn_state);
		btn_undo = (Button) this.findViewById(R.id.btn_undo);
		btn_save = (Button) this.findViewById(R.id.btn_save);
		btn_exit = (Button) this.findViewById(R.id.btn_exit);
		iv_add = (BeepImageButton) this.findViewById(R.id.iv_add);
		ibtn_backpage = (ImageButton) this.findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) this.findViewById(R.id.ibtn_nextpage);
		et_search = (EditText) this.findViewById(R.id.et_search);
		et_customer_no = (EditText) this.findViewById(R.id.et_customer_no);
		et_first_name = (EditText) this.findViewById(R.id.et_first_name);
		et_last_name = (EditText) this.findViewById(R.id.et_last_name);
		et_address_1 = (EditText) this.findViewById(R.id.et_address_1);
		et_address_2 = (EditText) this.findViewById(R.id.et_address_2);
		et_city = (EditText) this.findViewById(R.id.et_city);
		et_zip = (EditText) this.findViewById(R.id.et_zip);
		et_telephone = (EditText) this.findViewById(R.id.et_telephone);
		et_email = (EditText) this.findViewById(R.id.et_email);

		ll_main.setOnClickListener(mOnClickListener);
		btn_search.setOnClickListener(mOnClickListener);
		btn_save.setOnClickListener(mOnClickListener);
		btn_undo.setOnClickListener(mOnClickListener);
		btn_exit.setOnClickListener(mOnClickListener);
		btn_state.setOnClickListener(mOnClickListener);
		ibtn_backpage.setOnClickListener(mOnClickListener);
		ibtn_nextpage.setOnClickListener(mOnClickListener);
		iv_add.setOnClickListener(mOnClickListener);

		et_customer_no.addTextChangedListener(watcher);
		et_first_name.addTextChangedListener(watcher);
		et_last_name.addTextChangedListener(watcher);
		et_address_1.addTextChangedListener(watcher);
		et_address_2.addTextChangedListener(watcher);
		et_city.addTextChangedListener(watcher);
		et_zip.addTextChangedListener(watcher);
		et_telephone.addTextChangedListener(watcher);
		et_email.addTextChangedListener(watcher);
		btn_state.addTextChangedListener(watcher);

		lv_customer_list
				.setOnItemClickListener(onItemClickDialogWindowListener);
	}

	public void Search() {
		pageString = String.valueOf(tv_page.getText());
		SearchText = String.valueOf(et_search.getText());
		if (SearchText.trim().equals(""))
			return;
		int page = 0;

		switch ((int) sp_condition.getSelectedItemId()) {
		case CustomerSettingService.CustomerID:
			SearchType = CustomerSettingService.CustomerID;
			customerList = customerSettingService.getCustomerSetting(
					SearchType, page, SearchText);
			GetCountSize(SearchType, page, SearchText);
			break;
		case CustomerSettingService.FirstName:
			SearchType = CustomerSettingService.FirstName;
			customerList = customerSettingService.getCustomerSetting(
					SearchType, page, SearchText);
			GetCountSize(SearchType, page, SearchText);
			break;
		case CustomerSettingService.LastName:
			SearchType = CustomerSettingService.LastName;
			customerList = customerSettingService.getCustomerSetting(
					SearchType, page, SearchText);
			GetCountSize(SearchType, page, SearchText);
			break;
		}
		
		customerListAdapter = new SelectionAdapter(this, AdapterDataSourceBuilder.readValueFromCustomerSetting(customerList));
		lv_customer_list.setAdapter(customerListAdapter);
		customerListAdapter.ScrollToRow(0);
		lv_customer_list.setSelection(0);
		

		et_search.setText("");
		if (customerList.size() <= 0) {
			InitializationFalse();
			ControlEmpty();
			tv_page.setText("");
		} else {
			InitializationTrue();
			GetItemDetail(customerList.get(customerListAdapter
					.GetSelectedIndex()));
			tv_page.setText("1");
		}
		SetPage();
	}

	public void Save() {
		String cs_no, cs_last_name, cs_first_name, cs_address_1, cs_address_2, cs_city, cs_state, cs_zip, cs_telephone, cs_email, error, old_no;
		if (customerList == null || customerList.size() <= 0) {
			old_no = "0";
		} else {
			old_no = customerList.get(customerListAdapter.GetSelectedIndex())
					.getCs_no();
		}
		cs_no = String.valueOf(et_customer_no.getText()).trim();
		if (cs_no.equals("")) {
			ShowMessage("Customer no cannot be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return;
		}
		cs_first_name = String.valueOf(et_first_name.getText()).trim();
		cs_last_name = String.valueOf(et_last_name.getText()).trim();
		cs_address_1 = String.valueOf(et_address_1.getText()).trim();
		cs_address_2 = String.valueOf(et_address_2.getText()).trim();
		cs_city = String.valueOf(et_city.getText()).trim();
		cs_state = String.valueOf(btn_state.getText()).trim();
		cs_zip = String.valueOf(et_zip.getText()).trim();
		cs_telephone = String.valueOf(et_telephone.getText()).trim();
		cs_email = String.valueOf(et_email.getText()).trim();
		CustomerSetting item = new CustomerSetting();
		item.setCs_no(cs_no);
		item.setCs_first_name(cs_first_name);
		item.setCs_last_name(cs_last_name);
		item.setCs_address_1(cs_address_1);
		item.setCs_address_2(cs_address_2);
		item.setCs_city(cs_city);
		item.setCs_state(cs_state);
		item.setCs_zip(cs_zip);
		item.setCs_telephone(cs_telephone);
		item.setCs_email(cs_email);
		if (is_Insert) {
			List<CustomerSetting> Check = customerSettingService
					.getCustomerSettingId(cs_no);
			if (Check.size() > 0) {
				ShowMessage("Already exist for this customer no.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return;
			}
			error = customerSettingService.AddCustomerSetting(item);
			Check = customerSettingService
					.getCustomerSettingId(cs_no);
			if (GlobalInfo.getInstance().isMGNetwork) {
				if (Check != null && Check.size() > 0) {
					mMGCreateFiles.createrFile(Check.get(0).toMGData("INSERT"));
				}
			}
		} else {
			List<CustomerSetting> Check = customerSettingService
					.getCustomerSettingId(cs_no);
			if (!cs_no.equals(old_no)) {
				if (Check.size() > 0) {
					ShowMessage("Already exist for this customer no.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
			}
			error = customerSettingService.updateCustomerSetting(item, old_no);
			Check = customerSettingService
					.getCustomerSettingId(cs_no);
			if (GlobalInfo.getInstance().isMGNetwork) {
				if (Check != null && Check.size() > 0) {
					mMGCreateFiles.createrFile(Check.get(0).toMGData("UPDATE"));
				}
			}
		}
		if (error.length() > 0) {
			ShowMessage(error, MessageDialog.MESSAGE_BOX_OK,
					MessageDialog.ICON_INFO);
		} else {
			Toast.makeText(CustomerSettingActivity.this, "Save completed.",
					Toast.LENGTH_SHORT).show();
		}

		if (is_Insert) {
			customerList = customerSettingService.getCustomerSettingId(cs_no);
			customerListAdapter = new SelectionAdapter(
						CustomerSettingActivity.this, AdapterDataSourceBuilder.readValueFromCustomerSetting(customerList));
			lv_customer_list.setAdapter(customerListAdapter);
			customerListAdapter.ScrollToRow(0);
			lv_customer_list.setSelection(0);
		} else {
			RefreshListItem();
		}
		is_Insert = false;
		SetEnabledTrue();
	}

	public void RefreshListItem() {
		String pageString = (String) tv_page.getText();
		int page = 1;
		if (!pageString.trim().equals("")) {
			page = Integer.valueOf(pageString);
		}
		customerList = customerSettingService.getCustomerSetting(SearchType,
				page - 1, SearchText);
		customerListAdapter = new SelectionAdapter(this,AdapterDataSourceBuilder.readValueFromCustomerSetting(customerList) );
		lv_customer_list.setAdapter(customerListAdapter);
		if (customerList.size() <= 0) {
			InitializationFalse();
		} else {
			InitializationTrue();
			GetItemDetail(customerList.get(customerListAdapter
					.GetSelectedIndex()));
		}
	}

	public void GetItemDetail(CustomerSetting obj) {
		et_customer_no.setText(obj.getCs_no());
		et_first_name.setText(obj.getCs_first_name());
		et_last_name.setText(obj.getCs_last_name());
		et_address_1.setText(obj.getCs_address_1());
		et_address_2.setText(obj.getCs_address_2());
		et_city.setText(obj.getCs_city());
		btn_state.setText(obj.getCs_state());
		et_zip.setText(obj.getCs_zip());
		et_telephone.setText(obj.getCs_telephone());
		et_email.setText(obj.getCs_email());
	}

	public void GetCountSize(int searchType, int page, String SearchText) {
		long ItemCount = customerSettingService.GetCountSize(searchType,
				SearchText);
		long pageTemp = ItemCount % PageSize;
		if (pageTemp == 0) {
			PageCountSize = (int) ((ItemCount / PageSize));
		} else {
			PageCountSize = (int) ((ItemCount / PageSize) + 1);
		}
	}

	public void SetPage() {
		String pagetext = (String) tv_page.getText();
		if (pagetext.trim().equals("") || pagetext == null) {
			pagetext = "1";
		}
		int page = Integer.valueOf(pagetext);
		if (PageCountSize > page) {
			ibtn_nextpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_nextpage.setVisibility(View.INVISIBLE);
		}

		if (PageCountSize > 1 && page > 1) {
			ibtn_backpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_backpage.setVisibility(View.INVISIBLE);
		}
	}

	OnClickListener mOnClickListener = new OnClickListener() {
		String pagetext = "";
		int page = 0;

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.ll_main:
				Keyboard();
				break;
			case R.id.btn_search:
				CustomerMode = false;
				Search();
				Keyboard();
				CustomerMode = true;
				break;
			case R.id.btn_save:
				CustomerMode = false;
				Save();
				CustomerMode = true;
				break;
			case R.id.btn_undo:
				CustomerMode = false;
				if (customerList == null || customerList.size() <= 0) {
					InitializationFalse();
					ControlEmpty();
				} else {
					InitializationTrue();
					RefreshListItem();
				}
				SetEnabledTrue();
				is_Insert = false;
				CustomerMode = true;
				break;
			case R.id.btn_exit:
				isExit = true;
				ShowMessage(
						getResources().getString(R.string.msg_exit_program),
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			case R.id.btn_state:
				StateDialogWindow();
				break;
			case R.id.ibtn_backpage:
				CustomerMode = false;
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page - 1));
				customerList = customerSettingService.getCustomerSetting(
						SearchType, page - 2, SearchText);
				
				customerListAdapter = new SelectionAdapter(CustomerSettingActivity.this,AdapterDataSourceBuilder.readValueFromCustomerSetting(customerList) );
				
				customerListAdapter.ScrollToRow(0);
				lv_customer_list.setSelection(0);
				customerListAdapter.notifyDataSetChanged();
				GetItemDetail(customerList.get(customerListAdapter
						.GetSelectedIndex()));
				SetPage();
				CustomerMode = true;
				break;
			case R.id.ibtn_nextpage:
				CustomerMode = false;
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page + 1));
				customerList = customerSettingService.getCustomerSetting(
						SearchType, page, SearchText);
				customerListAdapter = new SelectionAdapter(CustomerSettingActivity.this,AdapterDataSourceBuilder.readValueFromCustomerSetting(customerList) );
			
				customerListAdapter.ScrollToRow(0);
				lv_customer_list.setSelection(0);
				customerListAdapter.notifyDataSetChanged();
				GetItemDetail(customerList.get(customerListAdapter
						.GetSelectedIndex()));
				SetPage();
				CustomerMode = true;
				break;
			case R.id.iv_add:
				et_customer_no.requestFocus();
				iv_add.setVisibility(View.INVISIBLE);
				is_Insert = true;
				ControlEmpty();
				InitializationTrue();
				SetEnabledFalse();
				break;
			default:
				break;
			}
		}

	};

	public OnClickListener OnClickDialogWindowListener = new OnClickListener() {

		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_states_dialog_ok:
				if (listStates.size() > 0) {
					btn_state.setText(listStates.get(
							stateAdapter.GetSelectedIndex()).getState_id());
				}
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_cancel:
				stateDialog.dismiss();
				break;
			case R.id.btn_states_dialog_search:
				String searchStates = et_states_dialog_search.getText()
						.toString();
				listStates = statesService.getStatesById(searchStates);
				stateAdapter.setSource(listStates);
				stateAdapter.notifyDataSetChanged();
				stateAdapter.ScrollToRow(0);
				et_states_dialog_search.setText("");
				break;
			}
		}
	};

	public OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (parent.getId()) {
			case R.id.lv_states_dialog_list:
				stateAdapter.ScrollToRow(position);
				break;
			case R.id.lv_customer_list:
				CustomerMode = false;
				customerListAdapter.ScrollToRow(position);
				GetItemDetail(customerList.get(position));
				CustomerMode = true;
				break;
			default:
				break;
			}

		}
	};

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
			if (CustomerMode) {
				SetEnabledFalse();
			}
		}

	};

	public void SetEnabledFalse() {
		sp_condition.setEnabled(false);
		lv_customer_list.setEnabled(false);
		btn_search.setEnabled(false);
		btn_exit.setEnabled(false);
		ibtn_backpage.setEnabled(false);
		ibtn_nextpage.setEnabled(false);
		iv_add.setEnabled(false);
		et_search.setEnabled(false);
		btn_save.setEnabled(true);
		btn_undo.setEnabled(true);
		iv_add.setVisibility(View.INVISIBLE);
	}

	public void SetEnabledTrue() {
		sp_condition.setEnabled(true);
		lv_customer_list.setEnabled(true);
		btn_search.setEnabled(true);
		btn_exit.setEnabled(true);
		ibtn_backpage.setEnabled(true);
		ibtn_nextpage.setEnabled(true);
		iv_add.setEnabled(true);
		et_search.setEnabled(true);
		btn_save.setEnabled(false);
		btn_undo.setEnabled(false);
		iv_add.setVisibility(View.VISIBLE);

	}

	public void InitializationFalse() {
		et_customer_no.setEnabled(false);
		et_first_name.setEnabled(false);
		et_last_name.setEnabled(false);
		et_address_1.setEnabled(false);
		et_address_2.setEnabled(false);
		et_city.setEnabled(false);
		et_zip.setEnabled(false);
		et_telephone.setEnabled(false);
		et_email.setEnabled(false);
		btn_state.setEnabled(false);
	}

	public void InitializationTrue() {
		et_customer_no.setEnabled(true);
		et_first_name.setEnabled(true);
		et_last_name.setEnabled(true);
		et_address_1.setEnabled(true);
		et_address_2.setEnabled(true);
		et_city.setEnabled(true);
		et_zip.setEnabled(true);
		et_telephone.setEnabled(true);
		et_email.setEnabled(true);
		btn_state.setEnabled(true);
	}

	public void ControlEmpty() {
		et_customer_no.setText("");
		et_first_name.setText("");
		et_last_name.setText("");
		et_address_1.setText("");
		et_address_2.setText("");
		et_city.setText("");
		et_zip.setText("");
		et_telephone.setText("");
		et_email.setText("");
		btn_state.setText("");
	}

	Dialog stateDialog = null;

	private void StateDialogWindow() {
		bindStateData();
		if (stateDialog == null) {
			stateDialog = new Dialog(this, R.style.Transparent_dialog);
			stateDialog.setContentView(R.layout.dialog_perview_states);
		}
		lv_states_dialog_list = (ListView) stateDialog
				.findViewById(R.id.lv_states_dialog_list);
		btn_states_dialog_ok = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_ok);
		btn_states_dialog_cancel = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_cancel);
		btn_states_dialog_search = (Button) stateDialog
				.findViewById(R.id.btn_states_dialog_search);
		et_states_dialog_search = (EditText) stateDialog
				.findViewById(R.id.et_states_dialog_search);
		btn_states_dialog_ok.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_cancel
				.setOnClickListener(OnClickDialogWindowListener);
		btn_states_dialog_search
				.setOnClickListener(OnClickDialogWindowListener);
		lv_states_dialog_list
				.setOnItemClickListener(onItemClickDialogWindowListener);
		
		if (stateAdapter == null) {
			stateAdapter = new StateListAdapter(this, listStates);
			lv_states_dialog_list.setAdapter(stateAdapter);
		} else {
			stateAdapter.setSource(listStates);
			stateAdapter.notifyDataSetChanged();
		}
		String stateString = btn_state.getText().toString().trim();
		if (stateString.equals("")) {
			stateAdapter.ScrollToRow(0);
			lv_states_dialog_list.setSelection(0);
		} else {
			for (int i = 0; i < listStates.size(); i++) {
				if (stateString.equals(listStates.get(i).getState_id())) {
					stateAdapter.ScrollToRow(i);
					lv_states_dialog_list.setSelection(i);
				}
			}
		}
		stateDialog.show();
	}

	private void bindStateData() {
		listStates = statesService.getStates();
	}

	public void ShowMessage(String text, int type, int icon) {
		if (mMessageDialog != null && mMessageDialog.isShowing()) {
			mMessageDialog.dismiss();
		}
		mMessageDialog = new MessageDialog(CustomerSettingActivity.this);
		mMessageDialog.setStyle(type);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(text);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			if (isExit) {
				isExit = false;
				finish();
			}

			mMessageDialog.dismiss();
		}

		@Override
		public void onClickNo() {
			// TODO Auto-generated method stub
			isExit = false;
			mMessageDialog.dismiss();
		}

		@Override
		public void onClickOK() {
			// TODO Auto-generated method stub
			mMessageDialog.dismiss();
		}

	};

	public void Keyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(CustomerSettingActivity.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

}
